<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
  },
}
</route>

<script setup>
import SortBar from '@/components/SortBar.vue'
import TopBar from '@/components/TopBar.vue'
import { goBack, judgeShowImage, uniNavigateTo } from '@/utils'
import OrderApi from '@/service/order'
import { useDictStore } from '@/store/dict'
import { getDictDetail, dictMap } from '@/service/dict'
import { useUserStore } from '@/store/user'
import { useMessage } from 'wot-design-uni'

// 获取状态栏高度
const { statusBarHeight } = uni.getSystemInfoSync()

const dictStore = useDictStore()

const userStore = useUserStore()

const message = useMessage()

onLoad(() => {
  // 监听预约成功事件
  uni.$on('bookingOrderSuccess', () => {
    refreshList()
  })
})

onUnload(() => {
  // 移除预约成功事件
  uni.$off('bookingOrderSuccess')
})

const tabList = ref([])
const activeTab = ref('')

const getDict = async () => {
  const { code, result } = await getDictDetail(dictMap.orderType)
  return code === 200 && result ? result : []
}
const initDict = async () => {
  const { orderType } = dictStore.dictData
  let dictItem = orderType
  if (!orderType) {
    dictItem = await getDict()
  }
  tabList.value = [{ label: '全部', value: '' }, ...dictItem]
  activeTab.value = tabList.value[0].value
}
initDict()

// const tabList = computed(() => {
//   const { orderType } = dictStore.dictData
//   return [{ label: '全部', value: '' }, ...orderType]
// })

const handleCheckTab = (val) => {
  activeTab.value = val
  refreshList()
}

const sortList = [
  { label: '点单最多', value: 'realTimes', type: 0 },
  { label: '最新发布', value: 'createTime', type: 2 }, // 默认按时间倒叙
]
const sortObj = ref({
  order: 'desc',
  column: 'createTime',
}) // 默认按时间倒叙

const handleCheckSort = (val) => {
  console.log('val', val)
  const { sortType, value } = val
  sortObj.value = {
    order: sortType,
    column: value,
  }
  refreshList()
}

/** ----------- 分页加载 start --------- */
const pageObj = ref({
  pageNo: 1,
  pageSize: 10,
})
const scrollState = reactive({
  refresherTriggered: false,
  dataList: [],
  loadState: 'loading',
})

const getDataList = async () => {
  if (scrollState.loadState === 'finished') return
  try {
    const params = {
      ...pageObj.value,
      type: activeTab.value,
      ...sortObj.value,
    }
    const { code, result } = await OrderApi.getShareOrderPage(params)
    if (code === 200 && result) {
      const { records, pages } = result
      if (records?.length) {
        scrollState.dataList = [...scrollState.dataList, ...records]
      }
      if (pageObj.value.pageNo < pages) {
        pageObj.value.pageNo++
      } else {
        scrollState.loadState = 'finished'
      }
    } else {
      scrollState.loadState = 'error'
    }
  } catch (e) {
    scrollState.loadState = 'error'
  }
}

const reset = () => {
  pageObj.value.pageNo = 1
  scrollState.dataList = []
  scrollState.loadState = 'loading'
}

const onRefresherrefresh = async () => {
  scrollState.refresherTriggered = true
  await refreshList()
  scrollState.refresherTriggered = false
}

const refreshList = async () => {
  try {
    uni.showLoading()
    reset()
    await getDataList()
  } finally {
    uni.hideLoading()
  }
}
refreshList()
/** ----------- 分页加载 end --------- */

const goPage = (path) => {
  console.log('path', path)
  if (userStore.isLogined) {
    uniNavigateTo(path)
  } else {
    message
      .confirm({
        msg: '您还未登录，是否去登录？',
        title: '提示',
      })
      .then(() => {
        uniNavigateTo('/pages/login/index')
      })
      .catch(() => {
        console.log('点击了取消按钮')
      })
  }
}
</script>

<template>
  <view class="common-page-bg">
    <view
      class="page-header"
      :style="{
        paddingTop: `${statusBarHeight}px`,
      }"
    >
      <!-- <image
        class="page-header-bg"
        src="@/static/images/menu-top-bg.png"
      ></image> -->
      <view class="page-header-nav">
        <view @tap="goBack()">
          <wd-icon
            name="chevron-left"
            size="56rpx"
            color="#fff"
          ></wd-icon>
        </view>
        <view class="page-header-nav-title">文化共享菜单</view>
      </view>
      <TopBar
        :tab-list="tabList"
        :active-tab="activeTab"
        @check="handleCheckTab"
      />
    </view>
    <view class="p-24rpx">
      <SortBar
        :sort-list="sortList"
        @check="handleCheckSort"
      />
    </view>
    <scroll-view
      class="scroll-container"
      scroll-y
      refresher-enabled
      enable-back-to-top
      :refresher-triggered="scrollState.refresherTriggered"
      @refresherrefresh="onRefresherrefresh"
      @scrolltolower="getDataList"
    >
      <template v-if="scrollState.dataList.length">
        <view class="flex flex-wrap">
          <view
            v-for="item in scrollState.dataList"
            :key="item.id"
            class="scroll-item-wrap"
          >
            <view
              class="scroll-item"
              @click="
                uniNavigateTo(
                  `/pages-sub/share-menu/detail/index?id=${item.id}`,
                )
              "
            >
              <image
                class="scroll-item-img"
                :src="judgeShowImage(item.coverUrl)"
              ></image>
              <view class="scroll-item-title ellipsis">{{ item.name }}</view>
              <view class="scroll-item-desc ellipsis">
                供单单位：{{ item.sysOrgCode_dictText }}
              </view>
              <view class="scroll-item-desc">
                剩余场次：{{ item.realResourceTimes }}
              </view>
            </view>
          </view>
        </view>
        <wd-loadmore
          finished-text="没有更多了"
          :state="scrollState.loadState"
          @reload="getDataList"
        />
      </template>
      <wd-status-tip
        v-else
        image="content"
        tip="暂无内容"
      />
    </scroll-view>
    <view
      class="float-btn"
      @click="goPage('/pages-sub/activity/add/index')"
    >
      <image
        class="w-full h-full"
        src="@/static/icons/float-btn-share.png"
      ></image>
    </view>

    <wd-message-box />
  </view>
</template>

<style lang="scss" scoped>
.common-page-bg {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.page-header {
  position: relative;
  z-index: 1;
  width: 100%;
  background-image: linear-gradient(90deg, #64e1ff 0%, #2f8de4 100%);
  box-sizing: border-box;

  &-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
  }

  &-nav {
    position: relative;
    z-index: 1;
    display: flex;
    align-items: center;
    // width: 100%;
    height: 88rpx;
    padding: 0 24rpx;

    &-title {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 32rpx;
      color: #fff;
      font-weight: 500;
    }
  }
}

.scroll-container {
  padding: 0 12rpx;
  box-sizing: border-box;
}

.scroll-item {
  padding: 24rpx 16rpx;
  background: #fff;
  border-radius: 16rpx;

  &-wrap {
    width: 50%;
    padding: 12rpx;
    box-sizing: border-box;
  }

  &-img {
    width: 100%;
    height: 208rpx;
    margin-bottom: 24rpx;
    border-radius: 16rpx;
  }

  &-title {
    margin-bottom: 16rpx;
    font-size: 28rpx;
    color: $uni-text-color;
    font-weight: 500;
  }

  &-desc {
    margin-bottom: 16rpx;
    font-size: 24rpx;
    color: $uni-text-color-grey;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.float-btn {
  position: fixed;
  bottom: 100rpx;
  right: 24rpx;
  z-index: 1;
  width: 128rpx;
  height: 128rpx;
}
</style>
